#! /usr/bin/python
# -*- coding: utf-8 -*-

import os
from google.appengine.ext.webapp import template
import cgi
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
import urllib
import conf
import utils
import utilsj
import permission
import paperbook
import paper
import adebook
import counters

class MainPage(webapp.RequestHandler):
    def get(self):
        cookieDict = utils.getXnCookieDict(self.request.cookies)
        xnuid = cookieDict.get('user')
        is_logged_in = utils.validateXnCookies(cookieDict, conf.app_secret)
        callbackUrl = utils.getUrlPathQuery(self.request)
        if not is_logged_in or not permission.hasResetCounterPermission(xnuid):
            self.redirect("/login?" + urllib.urlencode({'url':callbackUrl}))
            return None
        #get each mapping value
        paperEbookMappingList = []
        mappingModelList = paperbook.listAllAdebooks(0, 500)
        if mappingModelList:
            for mapping in mappingModelList:
                paperModel = paper.readPaperById(mapping.pid)
                if paperModel:
                    paperTitle = paperModel.title.encode('utf-8')
                else:
                    paperTitle = '没有对应的文章!'
                adebookModel = adebook.readAdebookById(mapping.ebid)
                if adebookModel:
                    ebookTitle = adebookModel.title.encode('utf-8')
                else:
                    ebookTitle = '没有对应的电子书!'
                newMappingInfo = {
                    'id': mapping.id,
                    'pid': mapping.pid,
                    'ebid': mapping.ebid,
                    'priority': mapping.priority,
                    'paperTitle': paperTitle,
                    'ebookTitle': ebookTitle
                }
                paperEbookMappingList.append(newMappingInfo)
        template_values = {
            'staticUrl': conf.staticUrl,
            'jsVersion': conf.jsVersion,
            'cssVersion': conf.cssVersion,
            'xnuid': xnuid,
            'nav_selected': 'ebook',
            'paperEbookMappingList': paperEbookMappingList
        }
        path = os.path.join(os.path.dirname(__file__), 'pages/admin/ebookmapping.html')
        self.response.out.write(template.render(path, template_values))

    def post(self):
        cookieDict = utils.getXnCookieDict(self.request.cookies)
        xnuid = cookieDict.get('user')
        is_logged_in = utils.validateXnCookies(cookieDict, conf.app_secret)
        callbackUrl = utils.getUrlPathQuery(self.request)
        if not is_logged_in or not permission.hasResetCounterPermission(xnuid):
            self.redirect("/login?" + urllib.urlencode({'url':callbackUrl}))
            return None

        op = self.request.get('op')
        if op not in ['new', 'del']:
            op = 'new'
        if op == 'del':
            return self.delMapping()
        else:
            return self.addMapping()

    def sucessResponse(self, respJson):
        self.response.headers['Content-Type'] = 'application/x-javascript'
        self.response.out.write(utilsj.serializeJson(respJson))
        return None
    def errorResponse(self, errCode):
        self.response.headers['Content-Type'] = 'application/x-javascript'
        respJson = {"errCode": errCode, "errMsg": paperbook.EBOOKMAPPING_ERROR_MESSAGES[errCode]}
        self.response.out.write(utilsj.serializeJson(respJson))
        return None

    def delMapping(self):
        mappingIdStr = self.request.get('id')
        try:
            mappingId = int(mappingIdStr)
        except ValueError:
            mappingId = 0
            return self.errorResponse(paperbook.EBOOKMAPPING_ERROR_CODE_LOSE_PARAMS)

        mappingModel = paperbook.readPaperBookMapping(mappingId)
        if not mappingModel:
            return self.errorResponse(paperbook.EBOOKMAPPING_ERROR_CODE_NOEXIST_MAPPING)

        paperbook.deletePaperBookMapping(mappingModel)
        #return success code!
        return self.errorResponse(paperbook.EBOOKMAPPING_ERROR_CODE_SUCCESS)

    def addMapping(self):
        pidStr = self.request.get('pid')
        try:
            pid = int(pidStr)
        except ValueError:
            pid = 0
            return self.errorResponse(paperbook.EBOOKMAPPING_ERROR_CODE_NOT_VALID_PID)
        
        ebidStr = self.request.get('ebid')
        try:
            ebid = int(ebidStr)
        except ValueError:
            ebid = 0
            return self.errorResponse(paperbook.EBOOKMAPPING_ERROR_CODE_NOT_VALID_EBID)
        
        priorityStr = self.request.get('priority')
        try:
            priority = int(priorityStr)
        except ValueError:
            priority = 0
            return self.errorResponse(paperbook.EBOOKMAPPING_ERROR_CODE_NOT_VALID_PRIORITY)
        if priority < 0:
            return self.errorResponse(paperbook.EBOOKMAPPING_ERROR_CODE_NOT_VALID_PRIORITY)

        paperModel = paper.readPaperById(pid)
        if not paperModel:
            return self.errorResponse(paperbook.EBOOKMAPPING_ERROR_CODE_NO_CORRESPONDING_PAPER)
        adebookModel = adebook.readAdebookById(ebid)
        if not adebookModel:
            return self.errorResponse(paperbook.EBOOKMAPPING_ERROR_CODE_NO_CORRESPONDING_EBOOK)
        
        mappingModel = paperbook.readPaperBookMappingBy2Ids(pid, ebid)
        if mappingModel:
            return self.errorResponse(paperbook.EBOOKMAPPING_ERROR_CODE_EXIST_MAPPING)
        
        mappingModel = paperbook.PaperBookMapping()
        counter = counters.AtomicCounter('paperebookmapping')
        mappingModel.id = counter.AtomicInc()
        mappingModel.pid = pid
        mappingModel.ebid = ebid
        mappingModel.priority = priority
        paperbook.writePaperBookMapping(mappingModel)
        
        respJson = {
            'id': mappingModel.id,
            'pid': mappingModel.pid,
            'ebid': mappingModel.ebid,
            'priority': mappingModel.priority,
            'paperTitle': paperModel.title.encode('utf-8'),
            'ebookTitle': adebookModel.title.encode('utf-8')
        }
        return self.sucessResponse(respJson)




application = webapp.WSGIApplication(
                                     [('/admin/ebookmapping', MainPage)],
                                     debug=True)
def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
